//! 执行上下文实现
//!
//! 提供查询执行过程中的全局状态管理

use super::*;
use std::time::Instant;

impl ExecutionContext {
    /// 创建新的执行上下文
    pub fn new(page_manager: Arc<PageManager>, transaction_id: u32) -> Self {
        Self {
            page_manager,
            transaction_id,
            table_metadata: HashMap::new(),
            statistics: ExecutionStatistics::default(),
            memory_limit: 64 * 1024 * 1024, // 默认64MB内存限制
            memory_usage: 0,
        }
    }
    
    /// 设置内存限制
    pub fn set_memory_limit(&mut self, limit: usize) {
        self.memory_limit = limit;
    }
    
    /// 检查内存使用是否超限
    pub fn check_memory_limit(&self, additional_bytes: usize) -> Result<()> {
        if self.memory_usage + additional_bytes > self.memory_limit {
            Err(Error::query_execution(format!(
                "内存使用超出限制: 当前{}MB + 请求{}MB > 限制{}MB",
                self.memory_usage / 1024 / 1024,
                additional_bytes / 1024 / 1024,
                self.memory_limit / 1024 / 1024
            )))
        } else {
            Ok(())
        }
    }
    
    /// 分配内存
    pub fn allocate_memory(&mut self, bytes: usize) -> Result<()> {
        self.check_memory_limit(bytes)?;
        self.memory_usage += bytes;
        
        // 更新峰值内存使用量
        if self.memory_usage > self.statistics.peak_memory_usage {
            self.statistics.peak_memory_usage = self.memory_usage;
        }
        
        tracing::debug!("分配内存: {}KB, 总使用: {}KB", 
            bytes / 1024, self.memory_usage / 1024);
        Ok(())
    }
    
    /// 释放内存
    pub fn deallocate_memory(&mut self, bytes: usize) {
        self.memory_usage = self.memory_usage.saturating_sub(bytes);
        tracing::debug!("释放内存: {}KB, 总使用: {}KB", 
            bytes / 1024, self.memory_usage / 1024);
    }
    
    /// 添加表元数据
    pub fn add_table_metadata(&mut self, metadata: TableMetadata) {
        tracing::debug!("添加表元数据: {}", metadata.name);
        self.table_metadata.insert(metadata.name.clone(), metadata);
    }
    
    /// 获取表元数据
    pub fn get_table_metadata(&self, table_name: &str) -> Option<&TableMetadata> {
        self.table_metadata.get(table_name)
    }

    /// 获取表模式
    pub fn get_table_schema(&self, table_name: &str) -> Result<ExecutionSchema> {
        if let Some(metadata) = self.get_table_metadata(table_name) {
            Ok(ExecutionSchema {
                columns: metadata.columns.clone(),
            })
        } else {
            Err(Error::query_execution(format!("表 {} 不存在", table_name)))
        }
    }

    /// 获取表（临时实现）
    pub fn get_table(&mut self, table_name: &str) -> Result<Arc<crate::storage::Table>> {
        // 这是一个临时实现，在真实系统中应该从存储引擎获取表
        Err(Error::query_execution(format!("表 {} 暂未实现", table_name)))
    }
    
    /// 更新算子统计信息
    pub fn update_operator_statistics(&mut self, operator_name: String, stats: OperatorStatistics) {
        self.statistics.operator_stats.insert(operator_name, stats);
    }
    
    /// 获取总执行统计信息
    pub fn get_execution_statistics(&self) -> &ExecutionStatistics {
        &self.statistics
    }
    
    /// 开始计时
    pub fn start_timer(&self) -> Instant {
        Instant::now()
    }
    
    /// 结束计时并更新统计
    pub fn end_timer(&mut self, start_time: Instant) {
        let elapsed = start_time.elapsed().as_micros() as u64;
        self.statistics.total_execution_time_us += elapsed;
    }
    
    /// 增加磁盘I/O计数
    pub fn increment_disk_io(&mut self, count: u64) {
        self.statistics.total_disk_io += count;
    }
    
    /// 获取当前内存使用率
    pub fn memory_usage_ratio(&self) -> f64 {
        self.memory_usage as f64 / self.memory_limit as f64
    }
    
    /// 检查是否需要内存回收
    pub fn should_trigger_gc(&self) -> bool {
        self.memory_usage_ratio() > 0.8 // 超过80%触发回收
    }
    
    /// 重置统计信息
    pub fn reset_statistics(&mut self) {
        self.statistics = ExecutionStatistics::default();
        self.memory_usage = 0;
    }
}

impl TableMetadata {
    /// 创建新的表元数据
    pub fn new(name: String, schema: ExecutionSchema) -> Self {
        Self {
            name,
            columns: schema.columns.clone(),
            root_page_id: None,
            row_count: 0,
            statistics: TableStatistics::default(),
        }
    }

    /// 设置根页面ID
    pub fn set_root_page_id(&mut self, page_id: u64) {
        self.root_page_id = Some(page_id);
    }

    /// 更新表统计信息
    pub fn update_statistics(&mut self, stats: TableStatistics) {
        self.statistics = stats;
    }

    /// 获取估计的行数
    pub fn estimated_row_count(&self) -> u64 {
        self.statistics.estimated_row_count
    }

    /// 获取列数量
    pub fn column_count(&self) -> usize {
        self.columns.len()
    }

    /// 根据名称查找列索引
    pub fn find_column_index(&self, column_name: &str) -> Option<usize> {
        self.columns.iter().position(|col| col.name == column_name)
    }
}

impl TableStatistics {
    /// 创建新的表统计信息
    pub fn new(row_count: u64, page_count: u64, avg_row_size: u32) -> Self {
        Self {
            estimated_row_count: row_count,
            page_count,
            average_row_size: avg_row_size,
            last_updated: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        }
    }
    
    /// 更新行数估计
    pub fn update_row_count(&mut self, new_count: u64) {
        self.estimated_row_count = new_count;
        self.update_timestamp();
    }
    
    /// 更新页面数量
    pub fn update_page_count(&mut self, new_count: u64) {
        self.page_count = new_count;
        self.update_timestamp();
    }
    
    /// 更新平均行大小
    pub fn update_average_row_size(&mut self, new_size: u32) {
        self.average_row_size = new_size;
        self.update_timestamp();
    }
    
    /// 更新时间戳
    fn update_timestamp(&mut self) {
        self.last_updated = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
    }
    
    /// 估算表大小（字节）
    pub fn estimated_table_size(&self) -> u64 {
        self.estimated_row_count * self.average_row_size as u64
    }
    
    /// 获取统计信息的年龄（秒）
    pub fn statistics_age(&self) -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            .saturating_sub(self.last_updated)
    }
    
    /// 检查统计信息是否过期
    pub fn is_stale(&self, max_age_seconds: u64) -> bool {
        self.statistics_age() > max_age_seconds
    }
}

impl ExecutionStatistics {
    /// 获取平均算子执行时间
    pub fn average_operator_time(&self) -> u64 {
        if self.operator_stats.is_empty() {
            0
        } else {
            let total_time: u64 = self.operator_stats.values()
                .map(|stats| stats.execution_time_us)
                .sum();
            total_time / self.operator_stats.len() as u64
        }
    }
    
    /// 获取最慢的算子
    pub fn slowest_operator(&self) -> Option<(&String, &OperatorStatistics)> {
        self.operator_stats.iter()
            .max_by_key(|(_, stats)| stats.execution_time_us)
    }
    
    /// 获取处理的总元组数
    pub fn total_tuples_processed(&self) -> u64 {
        self.operator_stats.values()
            .map(|stats| stats.tuples_processed)
            .sum()
    }
    
    /// 获取输出的总元组数
    pub fn total_tuples_output(&self) -> u64 {
        self.operator_stats.values()
            .map(|stats| stats.tuples_output)
            .sum()
    }
    
    /// 获取选择率
    pub fn selectivity(&self) -> f64 {
        let processed = self.total_tuples_processed();
        let output = self.total_tuples_output();
        
        if processed == 0 {
            0.0
        } else {
            output as f64 / processed as f64
        }
    }
    
    /// 获取总内存使用量
    pub fn total_memory_usage(&self) -> u64 {
        self.operator_stats.values()
            .map(|stats| stats.memory_usage_bytes)
            .sum()
    }
    
    /// 生成执行报告
    pub fn generate_report(&self) -> String {
        let mut report = String::new();
        
        report.push_str("执行统计报告\n");
        report.push_str("================\n");
        report.push_str(&format!("总执行时间: {}ms\n", self.total_execution_time_us / 1000));
        report.push_str(&format!("峰值内存使用: {}MB\n", self.peak_memory_usage / 1024 / 1024));
        report.push_str(&format!("总磁盘I/O: {}\n", self.total_disk_io));
        report.push_str(&format!("处理元组数: {}\n", self.total_tuples_processed()));
        report.push_str(&format!("输出元组数: {}\n", self.total_tuples_output()));
        report.push_str(&format!("选择率: {:.2}%\n", self.selectivity() * 100.0));
        
        if let Some((name, stats)) = self.slowest_operator() {
            report.push_str(&format!("最慢算子: {} ({}ms)\n", 
                name, stats.execution_time_us / 1000));
        }
        
        report.push_str("\n算子详情:\n");
        for (name, stats) in &self.operator_stats {
            report.push_str(&format!("  {}: {}ms, {}元组\n", 
                name, stats.execution_time_us / 1000, stats.tuples_processed));
        }
        
        report
    }
}
